package com.tongtong.stsuserapi.service.qiniu.Impl;


import com.tongtong.stscommon.enumration.Message;
import com.tongtong.stscommon.enumration.Status;
import com.tongtong.stscommon.message.STSMessage;
import com.tongtong.stscommon.message.STSSuccessMessage;
import com.tongtong.stscommon.utils.QiniuUtil;
import com.tongtong.stscommon.utils.checker.fileFormatChecker;
import com.tongtong.stsuserapi.service.qiniu.QiniuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Map;
import java.util.UUID;

@Service
public class QiniuServiceImpl implements QiniuService {

	@Autowired
	QiniuUtil qiniuUtil;

	@Override
	public Map<String,Object> Upload(MultipartFile file, String fileType) throws Exception {

		// 文件合法检查
		fileFormatChecker.isInvalidFormat(file,"image");

		// 获取文件的输入流
		InputStream inputStream = (InputStream)file.getInputStream();

		String uuidFileName= UUID.randomUUID().toString().replace("-","");
		String key = "image/"+fileType+"/"+uuidFileName;

		Map<String,Object> result;
		// 上传
		result = qiniuUtil.Upload(inputStream,key);

		return result;
	}

	@Override
	public STSMessage Delete(String url) throws Exception {
		// 删除
		String key = getExtension(url);
		qiniuUtil.Delete(key);
		return STSSuccessMessage.from(Status.OK, Message.OK);
	}

	private static String getExtension(String url) {
		String content = "";
		int dotComIndex = url.indexOf(".com/");

		if (dotComIndex > 0 && dotComIndex < url.length() - 1) {
			content = url.substring(dotComIndex + 5);
		}

		return content;
	}

}
